﻿@using Enter.Admin.Utils
@using Enter.Admin.Enums
@using Enter.Admin.Dtoes
@using Enter.Admin.Entities
@using Enter.Admin.Models.DataTables
@model HomeIndexModel
@{
    ViewData["Title"] = "档案管理";

    var enum_feild_map = new Dictionary<string, string>();

    var columns_SelectListItem = new List<SelectListItem>() { new SelectListItem { Text = "请选择", Value = "" } };
    var columns_Date_SelectListItem = new List<SelectListItem>() { new SelectListItem { Text = "请选择", Value = "" } };
    var columns_Enum_SelectListItem = new List<SelectListItem>() { new SelectListItem { Text = "请选择", Value = "" } };
    foreach (var item in Model.Columns.Where(t=>t.searchable))
    {
        var select_item = new SelectListItem { Text = item.title, Value = item.data };
        if (item.dataType == "DateTime")
        {
            columns_Date_SelectListItem.Add(select_item);
        }
        else if (!string.IsNullOrWhiteSpace(item.drop))
        {
            columns_Enum_SelectListItem.Add(select_item);
            enum_feild_map.Add(item.data, item.drop);
        }
        else
        {
            columns_SelectListItem.Add(select_item);
        }
    }
}
@section Styles {
    <link href="~/plugins/datatables.net-bs4/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-fixedcolumns-bs4/css/fixedColumns.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-select/css/select.dataTables.min.css" rel="stylesheet" />
    @*<link href="~/plugins/datatables.net-select-bs4/css/select.bootstrap4.min.css" rel="stylesheet" />*@
    <link href="~/plugins/dropzone/dist/min/dropzone.min.css" rel="stylesheet" />
    <link href="~/plugins/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet" />
    <link href="~/plugins/bootstrap-daterangepicker/daterangepicker.css" rel="stylesheet" />
    <link href="~/plugins/jquery-transfer/icon_font/css/icon_font.css" rel="stylesheet" />
    <link href="~/plugins/jquery-transfer/css/jquery.transfer.css" rel="stylesheet" />
    <style>
        .search-button-up {
            display: none
        }

        .search-button-row {
            display: none
        }

        div .bootstrap-select .btn.bs-placeholder {
            color: rgb(0,0,0) !important
        }

            div .bootstrap-select .btn.bs-placeholder:active, div .bootstrap-select .btn.bs-placeholder:focus, div .bootstrap-select .btn.bs-placeholder:hover {
                color: rgb(0,0,0) !important
            }

        div .bootstrap-select .btn.btn-light, div .bootstrap-select .btn.btn-white {
            color: rgb(0,0,0) !important
        }

        .btn-white:not(:disabled):not(.disabled).active, .btn-white:not(:disabled):not(.disabled):active, .show > .btn-white.dropdown-toggle {
            color: rgb(255,255,255) !important
        }
        #data-table-default {
            width: 100% !important;
        }
    </style>
}
@section Scripts {
    <script src="~/plugins/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="~/plugins/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="~/plugins/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
    <script src="~/plugins/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-fixedcolumns/js/dataTables.fixedColumns.min.js"></script>
    <script src="~/plugins/datatables.net-fixedcolumns-bs4/js/fixedColumns.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-select/js/dataTables.select.min.js"></script>
    <script src="~/plugins/datatables.net-select-bs4/js/select.bootstrap4.min.js"></script>
    <script src="~/plugins/dropzone/dist/min/dropzone.min.js"></script>
    <script src="~/plugins/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
    <script src="~/plugins/moment/min/moment.min.js"></script>
    <script src="~/plugins/bootstrap-daterangepicker/daterangepicker.js"></script>
    <script src="~/plugins/jquery-transfer/js/jquery.transfer.js?v=0.0.6"></script>
    <script>
        var currTableId = @Model.TableId ;
        var searchObj = function () {
            return {
                TableId: currTableId,
                Id: Number($('#Id').val()),
                BusinessNo: $('#BusinessNo').val(),
                ContractNo: $('#ContractNo').val(),

                SearchStringField: $('#SearchStringField').val(),
                SearchStringOperator: $('#SearchStringOperator').val(),
                SearchStringValue: $('#SearchStringValue').val(),
                SearchDateField: $('#SearchDateField').val(),
                SearchDateValue: $('#SearchDateValue').val(),
                SearchEnumField: $('#SearchEnumField').val(),
                SearchEnumValue: $('#SearchEnumValue').val(),

                FullText: $('.dataTables_filter input').val(),
            }
        }
        var enum_feild_map = @Html.Raw(Jsons.Serialize(enum_feild_map));
        var all_enums = @Html.Raw(Jsons.Serialize(EnumsExt.EnumMap));
        // @@Html.Raw(Json.Encode(Model.Data));
        //var columns_str = '@@(columns_json)'
        //columns_str = columns_str.replace(/&quot;/g,"\"")
        //var all_columns = JSON.parse(columns_str)
        var all_columns = @Html.Raw(Jsons.Serialize(Model.Columns));

        var transfer = null

        var case_allocation = function () {
            var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
            if (rows.length == 0) {
                show_alert('warning', "请选择需要分配的案件.")
                return
            }
            $("#modal-dialog-allocation").modal()
        }
        var case_allocation_ajax = function () {
            $("#modal-dialog-allocation-button").click(function () {
                var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
                var data = {
                    ArchiveIds: rows,
                    ChargeUserId: $("#AllocationUser").val()
                }
                $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(data),
                url: "@Url.Action("Allocation", "Home")",
                success: function (result) {
                    if (result.Success) {
                        $("#search-button").click()
                        $("#modal-dialog-allocation").modal('hide')
                        show_alert('success', result.Message)
                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
            })
        }

        var table_allocation = function () {
            var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
            if (rows.length == 0) {
                show_alert('warning', "请选择需要分配的案件.")
                return
            }
            $("#modal-dialog-table-allocation").modal()
        }
        var table_allocation_ajax = function () {
            $("#modal-dialog-table-allocation-button").click(function () {
                var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
                var data = {
                    ArchiveIds: rows,
                    TableId: $("#AllocationTable").val()
                }
                $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(data),
                url: "@Url.Action("AllocationTable", "Home")",
                success: function (result) {
                    if (result.Success) {
                        $("#search-button").click()
                        $("#modal-dialog-table-allocation").modal('hide')
                        show_alert('success', result.Message)
                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
            })
        }
        // 

        // https://www.cnblogs.com/chiakiyu/p/5436899.html
        var dataTable = null
        var params_table = null
        var handleDataTableDefault = function (tableId) {
            var columns = all_columns.slice()
            if (!isMobile) {
                columns.unshift({ title: '<input class="checkbox_all" type="checkbox"/>', orderable: false })
            }
            //columns[0].title = '<input class="checkbox_all" type="checkbox"/> 序号'
            columns.push({ data: "Id", title: '操作',  orderable: false })

            params_table = {
                    dom: 'lBfrtip',
                    buttons: [
                        {
                            text: '导入 <i class="fa fa-file-import"></i>',
                            className:'btn btn-primary',
                            action: function (e, dt, node, config) {
                                resetDropzone(0);
                                $('#modal-dialog-dropzone').modal();
                            }
                        },
                        {
                            text: '导出 <i class="fa fa-file-export"></i>',
                            className:'btn btn-primary',
                            action: function (e, dt, node, config) {
                                transfer_export();
                            }
                        },
                        {
                            text: '分配负责人 <i class="fas fa-thumbtack"></i>',
                            className: 'btn btn-primary',
                            action: function (e, dt, node, config) {
                                case_allocation()
                            }
                        },
                        {
                            text: '分配所属机构 <i class="fas fa-thumbtack"></i>',
                            className: 'btn btn-primary',
                            action: function (e, dt, node, config) {
                                table_allocation()
                            }
                        },
                        {
                            text: '新增 <i class="fa fa-plus"></i>',
                            className:'btn btn-primary',
                            action: function (e, dt, node, config) {
                                window.location.href = "@Url.Action("Edit", "Home")";
                            }
                        }
                    ],
                    responsive: isMobile, //是否显示全部
                    "searching": true,//datatables自带的搜索
                    "processing": true,//加载中
                "serverSide": true,
                    //"scrollX": true,
                //"sScrollX": true,
                "autoWidth": false,
                    //fixedColumns: {
                    //    leftColumns: 2,
                    //    rightColumns: 1,
                    //    "drawCallback": function () {
                    //        $(".DTFC_Cloned").css("width", "auto")
                    //        $(".DTFC_RightBodyLiner").css("overflow-y", "hidden")
                    //    }
                    //},
                    // 下一页更新复选框为不选中.
                    //fnDrawCallback: function () {
                    //    $('.checkbox_select').removeAttr("checked");
                    //    $('.checkbox_all').removeAttr("checked");
                    //},
                    "ajax": {
                        type: "POST",
                        url: '@Url.Action("LoadData", "Home")',
                        contentType: "application/json; charset=utf-8",
                        async: true,
                        headers: {
                            // https://www.cnblogs.com/liek/p/4884154.html
                           // "XSRF-TOKEN": document.querySelector('[name="__RequestVerificationToken"]').value
                            //"__RequestVerificationToken": $('[name="__RequestVerificationToken"]').val()
                        },
                        data: function (data) {
                            data.Data = searchObj()
                            data.columns = []
                            //data.__RequestVerificationToken = $('[name="__RequestVerificationToken"]').val()
                            return JSON.stringify(data);
                        }
                        //,
                        //"data": function (data) {
                        //    data.Name = $("#name").val();//此处是添加额外的请求参数
                        //    return JSON.stringify(data);
                        //}
                    },
                    //rowId: 'Id',
                    columns: columns,
                    //select: {
                    //    style: 'multi',
                    //    selector: 'td:first-child',//'td:first-child' 'td:not(:last-child)'
                    //    //blurable: true
                    //},
                    "columnDefs": [
                        //{
                        //    orderable: false,
                        //    className: 'select-checkbox',
                        //    targets: 0,
                        //    render: function (data, type, full, meta) {
                        //        return '';
                        //    }
                        //},
                        {
                            "targets": 1,
                            //className: 'select-checkbox',
                            render: function (data, type, full, meta) {
                                //return '<input class="checkbox_select" value = "' + full.Id + '" type="checkbox"/> ';// + full.Id;
                                return '<a class="btn btn-sm btn-info" target="_blank" href="@Url.Action("Detail", "Home")/' + full.Id + '">详情 <i class="fa fa-info"></i></a> ' + data;
                            }
                        },
                        {
                            "targets": -1,//-1表示最后一行 也可以是数组，"visible": false,"searchable": false
                            //"width": "220px",
                            render: function (data, type, full, meta) {
                                return '<a class="btn btn-sm btn-info" target="_blank" href="@Url.Action("Detail", "Home")/' + full.Id + '">详情 <i class="fa fa-info"></i></a>  '
                                    + '<a class="btn btn-sm btn-info" target="_blank" href="@Url.Action("Edit", "Home")/' + full.Id + '">修改 <i class="fa fa-edit"></i></a> ';
                                    //+ '<a class="btn btn-sm btn-info" href="javascript:;" onclick="modal_dialog_attachment_open({Id:' + full.Id + ',Name:\'' + full.ContractNo+'\'})">附件 <i class="fas fa-upload"></i></a>';

                                    //'<a class="btn btn-sm btn-info" href="javascript:;">删除<i class="fa fa-trash"></i></a> ';
                            }
                        }
                    ],
                    "language": datatable_language
                }
            if (!isMobile) {
                //params_table.fixedColumns = {
                //    //leftColumns: 2,
                //    rightColumns: 1,
                //    "drawCallback": function () {
                //        $(".DTFC_Cloned").css("width", "auto")
                //        $(".DTFC_RightBodyLiner").css("overflow-y", "hidden")
                //    }
                //}
                params_table.select = {
                    style: 'multi',
                    selector: 'td:first-child',//'td:first-child' 'td:not(:last-child)' '.DTFC_LeftBodyWrapper td:first-child'
                    //blurable: true
                }
                params_table.columnDefs.unshift({
                    orderable: false,
                    className: 'select-checkbox',
                    "width": "15px",
                    targets: 0,
                    render: function (data, type, full, meta) {
                        return '';
                    }
                })

            }
            dataTable = $('#data-table-default').DataTable(params_table);
            //dataTable.columns.adjust()
            // 取消datatabel的水平动作条，使用wrapAll在table上再包装一层div
            if (!isMobile) {
                $("#data-table-default").wrapAll("<div style='overflow-x:auto'>");
            }

        };

        Dropzone.autoDiscover = false;
        var dropzone_pre_file = null;
        var dropzone_file = function () {
            // http://www.voidcn.com/article/p-huweyrcj-bvo.html
            // http://www.renfei.org/blog/dropzone-js-introduction.html
            $("#dropzone-upload").dropzone({
                maxFiles: 1,
                url: "@Url.Action("Upload", "Home")",
                method: "post",
                acceptedFiles: ".xlsx",
                paramName: "files",
                addRemoveLinks: true,
                uploadMultiple: false,
                init: function () {
                    this.on("addedfile", function (file) {
                        if (dropzone_pre_file != null) {
                            this.removeFile(dropzone_pre_file);
                        }
                        dropzone_pre_file = file
                        //上传文件时触发的事件
                        //this.removeAllFiles();
                        //this.removeFile(file);
                    });
                    this.on("queuecomplete", function (file) {
                        //上传完成后触发的方法
                        //alert(2)
                    });
                    this.on("success", function (file,resp) {
                        //上传完成后触发的方法
                        if (resp.Success) {
                            $('#dropzone-upload-input').val(resp.Data)
                        } else {
                            $('#dropzone-upload-input').val('')
                            this.removeFile(dropzone_pre_file);
                            dropzone_pre_file = null
                            show_alert('warning', resp.Message)
                        }
                    });
                    this.on("removedfile", function (file) {
                        //删除文件时触发的方法
                        dropzone_pre_file = null
                        $('#dropzone-upload-input').val('')
                    });
                }
            });

        };

        var resetDropzone = function (id) {
            // https://stackoverflow.com/questions/31380478/reinitialize-reset-dropzone-after-form-is-submitted?noredirect=1
            dropzone_pre_file = null;
            $('#dropzone-container').empty();
            $('#dropzone-container').html($('#dropzone_template').html())
            function filesParamName() {
                return "files";
            }
            $("#dropzone-upload-input-id").val(id);
            var settlmentProofDropZone;
            $("#dropzone-upload").dropzone({
                maxFiles: id == 0 ? 1 : 5,
                url: "@Url.Action("Upload", "Home")" + (id == 0 ? "" : ("/" + id)),
                method: "post",
                acceptedFiles: id == 0 ? ".xlsx" : "",
                paramName: filesParamName,
                addRemoveLinks: id == 0,
                uploadMultiple: id > 0,
                init: function () {
                    settlmentProofDropZone = this;
                    this.on("addedfile", function (file) {
                        if (id == 0) {
                            if (dropzone_pre_file != null) {
                                this.removeFile(dropzone_pre_file);
                            }
                            dropzone_pre_file = file
                        }
                    });
                    this.on("success", function (file, resp) {
                        // 上传完成后触发的方法
                        if (resp.Success) {
                            $('#dropzone-upload-input').val(resp.Data)
                        } else {
                            $('#dropzone-upload-input').val('')
                            if (dropzone_pre_file != null) {
                                this.removeFile(dropzone_pre_file);
                            }
                            dropzone_pre_file = null
                            show_alert('warning', resp.Message)
                        }
                    });
                    this.on("removedfile", function (file) {
                        // 删除文件时触发的方法
                        dropzone_pre_file = null
                        $('#dropzone-upload-input').val('')
                    });
                }
            });
        }


        var data_table_attachment = null
        var modal_dialog_attachment_refresh = function (attachmentId, objectId) {
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                url: "@Url.Action("Attachment", "Home")" + "?id=" + attachmentId + "&objectId=" + objectId,
                success: function (result) {
                    if (result.Success) {
                        data_table_attachment.clear();
                        data_table_attachment.rows.add(result.Data);
                        data_table_attachment.draw();
                        $('#modal-dialog-attachment').modal();
                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
        }

        var modal_dialog_attachment_open = function (data) {
            $("#attachment-input-id").val(data.Id)
            $("#attachment-input-name").val(data.Name)
            modal_dialog_attachment_refresh(0, data.Id);
        }

        var modal_dialog_attachment_button = function () {
            // 上传附件
            $("#modal-dialog-attachment-button").click(function () {
                var a_id = $("#attachment-input-id").val();
                var a_name = $("#attachment-input-name").val();
                $('#modal-dialog-attachment').modal('hide');
                resetDropzone(a_id);
                $('#modal-dialog-dropzone').modal();
            })

            data_table_attachment = $('#data-table-attachment').DataTable({
                data: [],
                paging: false,
                "searching": false,
                dom: 'tip',
                columns: [{ title: "文件", data: "Name" }, { title: "操作", data: "Id" }],
                "columnDefs": [
                    {
                        "targets": -1,
                        "width": "150px",
                        render: function (data, type, full, meta) {
                            return '<a class="btn btn-sm btn-info" target="_blank" href="@Url.Action("Export", "Home")/' + full.Id + '">下载 <i class="fas fa-download"></i></a>  '
                                + '<a class="btn btn-sm btn-info" href="javascript:;" onclick="modal_dialog_attachment_refresh(' + full.Id + ',' + full.ObjectId + ')">删除 <i class="fa fa-trash"></i></a> ';
                        }
                    }
                ],
                "language": datatable_language
            });
        }


        // 导入;
        var import_excel = function () {
            var file_id = $("#dropzone-upload-input-id").val()
            if (file_id != "0") {
                // 显示附件列表;
                $('#modal-dialog-dropzone').modal('hide')
                modal_dialog_attachment_refresh(0, file_id);
                $('#modal-dialog-attachment').modal();
                return
            }
            var file_name = $('#dropzone-upload-input').val()
            if (!file_name) {
                show_alert('warning', '请选择文件.')
            } else {
                show_ajax();
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "@Url.Action("Import", "Home")",// ,new {id = Model.Id }
                    data: {
                        fileName: file_name,
                    },
                    success: function (result) {
                        if (result.Success) {
                            show_alert('success', result.Message)
                            $('#dropzone-upload-input').val('')
                            $('#modal-dialog-dropzone').modal('hide')
                            $("#search-button").click()
                        } else {
                            show_alert('warning', result.Message)
                        }
                        hide_ajax()
                    },
                    error: function (e) {
                        show_alert('error', '网络异常.')
                        hide_ajax()

                    },
                    complete: function (XMLHttpRequest, status) {
                        hide_ajax()
                    }
                });
            }
        }

        var default_selected = []// ["Id", "ContractNo"]
        var transfer_export = function () {
            var dataArray = []
            //var columns = all_columns.slice()
            for (let i = 0; i < all_columns.length; i++) {
                var item = all_columns[i]
                if (item.export) {
                    dataArray.push({
                        "data": item.data,
                        "title": item.title,
                        "selected": default_selected.includes(item.data)
                    })
                }
            }
            var settings1 = {
                "dataArray": dataArray,
                "itemName": "title",
                "valueName": "data",
                tabNameText: "未选择的项",
                rightTabNameText: "已选择的项",
                searchPlaceholderText: "搜索",
                //"callable": function (items) {
                //    console.dir(items)
                //}
            };
            $("#transfer-export").empty()
            transfer = $("#transfer-export").transfer(settings1);
            $('#modal-dialog-export').modal();
        }

        var export_excel_button = function () {
            var columns = transfer.getSelectedItems().map(({ data }) => (data));
            var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
            // var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => ({ Id }));

            var data = {
                Data: searchObj(),
                Columns: columns,
                Rows: rows
            }
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                url: "@Url.Action("Export", "Home")",// ,new {id = Model.Id }
                data: JSON.stringify(data),
                success: function (result) {
                    if (result.Success) {
                        window.location.href = "@Url.Action("Export", "Home")" + "/" + result.Data
                        $('#modal-dialog-export').modal('hide')
                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
        }

        var date_range_select = function () {
            var daterangepicker_id1 = '#SearchDateValue'
            $(daterangepicker_id1).daterangepicker({
                format: 'YYYY-MM-DD',
                autoUpdateInput: false,
                //startDate: moment().subtract(29, 'days'),
                //endDate: moment(),
                minDate: '1970-01-01',
                maxDate: '2050-12-31',
                //dateLimit: { days: 60 },
                //showDropdowns: true,
                //showWeekNumbers: true,
                alwaysShowCalendars:true,
                timePicker: false,
                timePickerIncrement: 1,
                timePicker12Hour: false,
                ranges: {
                    '今天': [moment(), moment()],
                    '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    '最近一周': [moment().subtract(6, 'days'), moment()],
                    '这个月': [moment().startOf('month'), moment().endOf('month')],
                    '上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                },
                opens: 'right',
                drops: 'down',
                buttonClasses: ['btn', 'btn-sm'],
                applyClass: 'btn-primary',
                cancelClass: 'btn-default',
                separator: ' to ',
                locale: {
                    format: 'YYYY-MM-DD',
                    applyLabel: '确定',
                    cancelLabel: '清除',
                    fromLabel: 'From',
                    toLabel: 'To',
                    customRangeLabel: '自定义',
                    daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                    firstDay: 1
                }
            }, function (start, end, label) {
                    $(daterangepicker_id1).val(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
            });
            $(daterangepicker_id1).on('cancel.daterangepicker', function (ev, picker) {
                //做点什么，比如清除输入
                $(daterangepicker_id1).val('');
            });
        }

        var select_enum_change = function () {
            $("#SearchEnumField").change(function () {
                $("#SearchEnumValue").empty();
                var s_v = $(this).val();
                if (s_v != "")
                {
                    var arr = all_enums[enum_feild_map[s_v]]

                    for (j = 0; j < arr.length; j++) {
                        var option = $("<option>").val(arr[j]["Value"]).text(arr[j]["Text"]);
                        $("#SearchEnumValue").append(option);
                    }
                    $("#SearchEnumValue").selectpicker('refresh');
                }
            });
        }



        var dynamic_columns = function (tableId) {
            if (tableId == currTableId) {
                return
            }
            currTableId = tableId

            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                url: "@Url.Action("Columns", "Home")" + "/" + currTableId,
                //data: JSON.stringify(data),
                success: function (result) {
                    if (result.Success) {
                        all_columns = result.Data

                        dataTable.clear(); //清空一下table
                        dataTable.destroy(); //还原初始化了的dataTable
                        $('#data-table-default').empty();

                        handleDataTableDefault(currTableId);

                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
            return
        }

        $(document).ready(function () {
            handleDataTableDefault(currTableId);
            $('.selectpicker').selectpicker('render');
            //dropzone_file();
            date_range_select();
            select_enum_change();
            modal_dialog_attachment_button();
            case_allocation_ajax();
            table_allocation_ajax();
            $("#dropzone-upload-button").click(function () {
                import_excel();
            });

            $("#search-button").click(function () {
                if (dataTable != null) {
                    //dataTable.ajax.reload();
                    dataTable.search($('.dataTables_filter input').val()).draw();
                }
            });

            $("#export-button").click(function () {
                export_excel();
            });

            $("#modal-dialog-export-button").click(function () {
                export_excel_button();
            });

            $(".search-button-down").click(function () {
                $(".search-button-up").show();
                $(".search-button-row").css('display', 'flex')
                $(".search-button-down").hide();
            })
            $(".search-button-up").click(function () {
                $(".search-button-up").hide();
                $(".search-button-row").hide();
                $(".search-button-down").show();
            })

            $('.dataTables_filter input').unbind();// .off();

            // https://blog.csdn.net/nihaoqiulinhe/article/details/53412077
            // https://blog.csdn.net/zxc84265137/article/details/83576661
            $("#data-table-default").on("click", ".checkbox_all", function (e) {
                // data-table-default_wrapper
                // ".DTFC_LeftHeadWrapper .checkbox_all"
                if (this.checked) {
                    dataTable.rows().select();
                     //var count = dataTable.rows( { selected: true } ).count();
                    //$('.DTFC_LeftBodyWrapper .checkbox_select').attr("checked", 'true')
                    //$('.checkbox_select').each(function () {
                    //    this.checked = true;
                    //});
                }
                else {
                    dataTable.rows().deselect();
                    //$('.DTFC_LeftBodyWrapper .checkbox_select').removeAttr("checked")
                    //$('.checkbox_select').each(function () {
                    //    this.checked = false;
                    //});
                }
            });

            $("input:radio[name=dynamic_options]").click(function () {
                dynamic_columns($(this).attr("data-id"))
                //alert($(this).attr("data-id"))
                //alert(this.checked)
                // Get the column API object dynamic_columns
                //var column = dataTable.column(0);
                //// Toggle the visibility
                //column.visible(!column.visible());
            })
        });

    </script>
}

<script type="text/html" id="dropzone_template">
    <form asp-action="Import" class="dropzone needsclick" enctype="multipart/form-data" id="dropzone-upload">
        <input type="text" id="dropzone-upload-input" style="display:none" class="form-control" />
        <input type="text" id="dropzone-upload-input-id" style="display:none" class="form-control" />
        <div class="dz-message needsclick">
            点击选择文件
        </div>
    </form>
</script>
<!-- begin breadcrumb -->
<ol class="breadcrumb float-xl-right">
    <li class="breadcrumb-item"><a href="javascript:;">资料管理</a></li>
    <li class="breadcrumb-item active">档案管理</li>
</ol>
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">档案管理 <small>...</small></h1>
<!-- end page-header -->
<!-- begin panel -->
<div class="panel panel-inverse">
    <!-- begin panel-heading -->
    <div class="panel-heading">
        <h4 class="panel-title">档案列表</h4>
        <div class="btn-group btn-group-toggle" data-toggle="buttons">
            <label class="btn btn-primary btn-xs @(Model.TableId == 0?"active":"")">
                <input type="radio" name="dynamic_options" data-id="0" @(Model.TableId == 0?"checked":"")/> 全部列
            </label>
            @foreach (var tb in Model.Tables)
            {
                <label class="btn btn-primary btn-xs @(Model.TableId == tb.Id?"active":"")" @(Model.TableId == tb.Id?"checked":"")>
                    <input type="radio" name="dynamic_options" data-id="@tb.Id" /> @tb.Name
                </label>
            }
        </div>
        <div class="panel-heading-btn" style="padding-left: 10px;">
            <a href="@Url.Action("Index", "Template")" class="btn btn-xs btn-primary"><i class="fas fa-cogs"></i></a>
        </div>
    </div>
    <!-- end panel-heading -->
    <div class="panel-body">
        <div class="row m-b-5">
            <div class="col-md-3 m-b-5">
                <div class="input-group">
                    <div class="input-group-prepend"><span class="input-group-text">序号:</span></div>
                    <input type="number" id="Id" class="form-control" />
                </div>
            </div>
            <div class="col-md-3 m-b-5">
                <div class="input-group">
                    <div class="input-group-prepend"><span class="input-group-text">合同编号:</span></div>
                    <input type="text" id="ContractNo" class="form-control" />
                </div>
            </div>
            <div class="col-md-3 m-b-5">
                <div class="input-group">
                    <div class="input-group-prepend"><span class="input-group-text">借据编号:</span></div>
                    <input type="text" id="BusinessNo" class="form-control" />
                </div>
            </div>
            <div class="col-md-3 text-right">
                <!--在Bootstrap 4中，pull-right样式类已经更名为float-right类名了-->
                <!--
            <a href="#modal-dialog" class="btn btn-primary" data-toggle="modal">导入 <i class="fa fa-file-import"></i></a>
            <button type="button" id="export-button" class="btn btn-primary">导出 <i class="fa fa-file-export"></i></button>
            -->
                <button type="button" id="search-button" class="btn btn-primary">搜索 <i class="fas fa-search-plus"></i></button>
                <button type="button" class="btn btn-primary search-button-down"><i class="fas fa-angle-double-down"></i></button>
                <button type="button" class="btn btn-primary search-button-up"><i class="fas fa-angle-double-up"></i></button>

            </div>
        </div>
        <div class="row search-button-row">
            <div class="col-md-4 m-b-5">
                <div class="input-group">
                    @Html.DropDownList("SearchStringField", columns_SelectListItem, new { @class = "form-control selectpicker", @data_live_search = "true" })
                    <select class="form-control selectpicker" data-live-search="true" id="SearchStringOperator" name="SearchStringOperator">
                        <option value="Eq">等于</option>
                        <option value="Contains">包含</option>
                        <option value="StartsWith">以开始</option>
                        <option value="EndsWith">以结束</option>
                        <option value="NotContains">不包含</option>
                        <option value="NotEqual">不等于</option>
                        <option value="GreaterThanOrEqual">大于等于</option>
                        <option value="LessThanOrEqual">小于等于</option>
                        <option value="Range">范围</option>
                    </select>
                    <input type="text" id="SearchStringValue" class="form-control" />
                </div>
            </div>
            <div class="col-md-4 m-b-5">
                <div class="input-group">
                    @Html.DropDownList("SearchDateField", columns_Date_SelectListItem, new { @class = "form-control selectpicker", @data_live_search = "true" })
                    <input type="text" id="SearchDateValue" class="form-control" />
                </div>
            </div>
            <div class="col-md-4 m-b-5">
                <div class="input-group">
                    @Html.DropDownList("SearchEnumField", columns_Enum_SelectListItem, new { @class = "form-control selectpicker", @data_live_search = "true" })
                    <select class="form-control selectpicker" data-live-search="true" data-style="btn-white" id="SearchEnumValue" name="SearchEnumValue">
                        <option value="">请选择</option>
                    </select>
                    <!---->
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-dropzone" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">上传</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div id="dropzone-container">

                        </div>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="dropzone-upload-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-attachment" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">附件列表</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <input type="text" id="attachment-input-id" style="display:none" class="form-control" />
                        <input type="text" id="attachment-input-name" style="display:none" class="form-control" />
                        <div id="attachment-container">
                            <table id="data-table-attachment" class="table table-striped table-bordered table-td-valign-middle display nowrap" style="width:100%">
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-attachment-button" class="btn btn-primary">上传附件</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-export" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">选择导出项</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div id="transfer-export" class="transfer-demo"></div>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-export-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-allocation" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">分配</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label class="col-form-label">负责人</label>
                            @Html.DropDownList("AllocationUser", Tools.EnumList(nameof(EnumArchive.EnumEmploy), false), new { @class = "form-control selectpicker", @data_live_search = "true" })
                        </div>

                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-allocation-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-table-allocation" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">分配所属机构</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label class="col-form-label">所属机构</label>
                            @Html.DropDownList("AllocationTable", Tools.EnumList(nameof(EnumArchive.EnumDynamicTable), false), new { @class = "form-control selectpicker", @data_live_search = "true" })
                        </div>

                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-table-allocation-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- begin panel-body -->
    <div class="panel-body">
        <form id="form-delete" style="display:none">@Html.AntiForgeryToken()</form>
        <table id="data-table-default" class="table table-striped table-bordered table-td-valign-middle display nowrap" style="width:100%">
        </table>
    </div>
    <!-- end panel-body   -->
</div>
<!-- end panel -->
